<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Arr;

/**
 * Class ModelCommand
 * @package App\Console\Commands
 */
class FormatCommand extends Command {
    /**
     * @var string
     */
    protected $signature = 'create:format {--table=} {--path=}';
    /**
     * @var string
     */
    protected $basePath = 'app/Format';
    use CommandTrait;

    /**
     * @name: handle
     * @author: lisa
     * @datetime: 2021/8/3 10:37
     */
    public function handle() {
        $table = $this->option('table');
        $basePath = $this->option('path');
        $this->basePath = $basePath ?: $this->basePath;
        if (!$table) $this->error('请输入表名');
        if (!$this->isTableExists($table)) $this->error("该表不存在");
        $fileName  = \Str::singular($table) . "Format.php";
        $functionName = \Str::studly(\Str::singular($table));
        $fileName  = $this->getFileName($fileName);
        $path      = $this->getPath($fileName);
        $structure = $this->getTableStructure($table);
        list($namespace, $className) = $this->getNamespaceAndClassName($path);
        list($columns) = $this->getTableColumns($structure);
        $this->render($path, [
            'table'         => $table,
            'namespace'     => $namespace,
            'className'     => $className,
            'columns'       => $columns,
            'functionName'  => $functionName,
        ], $this->getRenderHtml());
    }

    /**
     * 获取表列、主键、查询条件
     * @param $tableStructure
     * @name: getTableColumnsAndPrimaryKeyAndWhereSymbols
     * @return array
     * @author: lisa
     * @datetime: 2021/8/3 11:09
     */
    public function getTableColumns($tableStructure): array
    {
        $columns = [];
        foreach ($tableStructure as $k => $v) {
            $field = Arr::get($v, 'Field');
            $columns[] = $field;
        }
        $columns = $this->createPreFormatString($columns);
        return [$columns];
    }

    /**
     * @name: getRenderHtml
     * @return string
     * @author: lisa
     * @datetime: 2021/8/3 11:53
     */
    public function getRenderHtml() {
        return <<<html
<?php
namespace {namespace};
use App\Format\BaseFormat;

class {className} extends BaseFormat
{
    // 后台-列表
    public static function formatBg{functionName}List(\$list)
    {
        \$data = [];
        foreach (\$list as \$resource) {
            \$data[] = {columns};
        }
        return \$data;
    }

    // 后台-详情
    public static function formatBg{functionName}Detail(\$resource)
    {
        \$data = {columns};
        return \$data;
    }
}
html;
    }

}
